<?php

namespace App\Models;

use App\Mail\ConfirmEmail;
use App\Models\Traits\ActiveUserHelper;
use App\Models\Traits\NewUserHelper;
use App\Models\Traits\RecordLastLoginHelper;
use Illuminate\Auth\MustVerifyEmail;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable implements \Illuminate\Contracts\Auth\MustVerifyEmail
{
    use Notifiable;
    use MustVerifyEmail;
    use ActiveUserHelper;
    use NewUserHelper;
    use RecordLastLoginHelper;
    use HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password','is_admin','introduction','image','last_login_time',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected static function boot()
    {
        parent::boot();
    }

    public function posts() {
        return $this->hasMany(Post::class);
    }

    public function followers() {
        return $this->belongsToMany(User::class,'follows','user_id','follower_id');
    }

    public function followings() {
        return $this->belongsToMany(User::class,'follows','follower_id','user_id');
    }

    public function isFollowing($user_id) {
        return $this->followings->contains($user_id);
    }

    public function follow($id) {

        if (!is_array($id)) {
            $id = compact('id');
        }
        return $this->followings()->sync($id,false);
    }

    public function unfollow($user_id) {
        if (!is_array($user_id)) {
            $user_id = compact('user_id');
        }
        $this->followings()->detach($user_id);
    }

}
